﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using App_Code.Modules;
using Portal.Data.Entity;

public partial class Modules_Permission_Select : PermissionModule
{
    private static IList modules;
    private static IList categories;

    //general 
    private const string CHECKBOX_VIEW_ADMIN_TOOL = "cb_viewadmintool_";

    private const string CHECKBOX_MODULE_VIEW = "cb_view_";
    private const string CHECKBOX_MODULE_EDIT = "cb_edit_";
    private const string CHECKBOX_MODULE_DELETE = "cb_delete_";

    //    private const string CHECKBOX_CAT_DRAFT = "cb_cat_draft";
    private const string CHECKBOX_CAT_SUBMIT = "cb_cat_submit";
    private const string CHECKBOX_CAT_APPROVE = "cb_cat_approve";
    private const string CHECKBOX_CAT_PUBLISH = "cb_cat_publish";

    private static List<Control> GeneralControls = new List<Control>();
    private static List<Control> ModuleControls = new List<Control>();
    private static List<Control> CategoryControls = new List<Control>();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            categories = (IList)Category.ListAll();
            modules = (IList)Module.ListAll();
            dlUser.DataSource = PortalUser.ListAll();
            dlUser.DataBind();
        }
        else
        {
            //recreated controls from memory
            RebuildFromList();
        }
    }

    void BindPermission()
    {
        int roleId = Convert.ToInt32(dlUser.SelectedValue);
        PortalObject po;
        string cssAlter;
        int i = 1;
        Permission p;

        ClearControls();
        ClearControlsInList();

        //for GENERAL
        p = Permission.Load(roleId, Permission.VIEW_ADMIN_TOOL);
        AddGeneralLitteral("<tr><td>Sử dụng công cụ admin</td><td>");
        AddGeneralCheckBox(CHECKBOX_VIEW_ADMIN_TOOL, p != null);
        AddGeneralLitteral("</td></tr>");

        //for MODULES
        foreach (Module m in modules)
        {
            cssAlter = i % 2 == 0 ? "class='cssAlter'" : "";
            po = PortalObject.FindByPrimaryKey(m.ID);
            p = Permission.Load(roleId, po.ID);

            AddModuleLitteral("<tr " + cssAlter + ">");

            //add name
            AddModuleLitteral("<td class='name'>");
            AddModuleLitteral(m.Name);
            AddModuleLitteral("</td>");

            //
            //add Can view
            AddModuleLitteral("<td>");
            AddModuleCheckBox(CHECKBOX_MODULE_VIEW + m.ID, p, Permission.MODULE_VIEW);
            AddModuleLitteral("</td>");
            //
            //add Can Edit
            AddModuleLitteral("<td>");
            AddModuleCheckBox(CHECKBOX_MODULE_EDIT + m.ID, p, Permission.MODULE_EDIT);
            AddModuleLitteral("</td>");

            //
            //add Can delete
            AddModuleLitteral("<td>");
            AddModuleCheckBox(CHECKBOX_MODULE_DELETE + m.ID, p, Permission.MODULE_DELETE);
            AddModuleLitteral("</td>");

            //
            AddCategoryLitteral("</tr>");
            i++;
        }
        i = 1;
        //FOR Categories
        foreach (Category cat in categories)
        {
            cssAlter = i % 2 == 0 ? "class='cssAlter'" : "";
            po = PortalObject.FindByPrimaryKey(cat.ID);
            p = Permission.Load(roleId, po.ID);

            AddCategoryLitteral("<tr " + cssAlter + ">");

            //add name
            AddCategoryLitteral("<td class='name'>");
            AddCategoryLitteral(cat.DisplayFullName);
            AddCategoryLitteral("</td>");

            //add Can WF_SUBMIT
            AddCategoryLitteral("<td>");
            AddCategoryCheckBox(CHECKBOX_CAT_SUBMIT + cat.ID, p, Permission.WF_SUBMIT);
            AddCategoryLitteral("</td>");

            //
            //add Can WF_APPROVE
            AddCategoryLitteral("<td>");
            AddCategoryCheckBox(CHECKBOX_CAT_APPROVE + cat.ID, p, Permission.WF_APPROVE);
            AddCategoryLitteral("</td>");

            //
            //add Can PUBLISH
            AddCategoryLitteral("<td>");
            AddCategoryCheckBox(CHECKBOX_CAT_PUBLISH + cat.ID, p, Permission.WF_PUBLISH);
            AddCategoryLitteral("</td>");

            //
            AddCategoryLitteral("</tr>");
            i++;
        }
    }

    #region methods for Module block
    void AddGeneralLitteral(string text)
    {
        LiteralControl ltr = new LiteralControl(text);
        phGeneral.Controls.Add(ltr);
        GeneralControls.Add(ltr);
    }
    void AddGeneralCheckBox(string controlId, bool canbe)
    {
        CheckBox cb = new CheckBox();
        cb.ID = controlId;
        cb.Checked = canbe;
        phGeneral.Controls.Add(cb);
        GeneralControls.Add(cb);
    }
    void AddModuleCheckBox(string controlId, Permission p, int permisionCompare)
    {
        CheckBox cb = new CheckBox();
        cb.ID = controlId;
        cb.Checked = CheckIsCanbe(p, permisionCompare);
        phModule.Controls.Add(cb);
        ModuleControls.Add(cb);
    }
    void AddModuleLitteral(string text)
    {
        LiteralControl ltr = new LiteralControl(text);
        phModule.Controls.Add(ltr);
        ModuleControls.Add(ltr);
    }
    #endregion

    #region methods for Category block
    void AddCategoryCheckBox(string controlId, Permission p, int permisionCompare)
    {
        CheckBox cb = new CheckBox();
        cb.ID = controlId;
        cb.Checked = CheckIsCanbe(p, permisionCompare);
        phCategory.Controls.Add(cb);
        CategoryControls.Add(cb);
    }
    void AddCategoryLitteral(string text)
    {
        LiteralControl ltr = new LiteralControl(text);
        phCategory.Controls.Add(ltr);
        CategoryControls.Add(ltr);
    }
    #endregion
    void ClearControls()
    {
        phGeneral.Controls.Clear();
        phModule.Controls.Clear();
        phCategory.Controls.Clear();
    }
    void ClearControlsInList()
    {
        GeneralControls.Clear();
        ModuleControls.Clear();
        CategoryControls.Clear();
    }
    void RebuildFromList()
    {
        ClearControls();
        //fore general
        for (int i = 0; i < GeneralControls.Count; i++)
        {
            phGeneral.Controls.Add(GeneralControls[i]);
        }

        //for MODULES
        for (int i = 0; i < ModuleControls.Count; i++)
        {
            phModule.Controls.Add(ModuleControls[i]);
        }
        //FOR Categories
        for (int i = 0; i < CategoryControls.Count; i++)
        {
            phCategory.Controls.Add(CategoryControls[i]);
        }
    }
    bool CheckIsCanbe(Permission permission, int pCheck)
    {
        if (permission == null)
            return false;

        return Permission.HasPermission(permission.Permissions, pCheck);
    }
    protected void View_Click(object sender, EventArgs e)
    {
        phPermission.Visible = true;
        message.Text = "";
        BindPermission();
    }
    protected override void Cancel_Click(object sender, EventArgs e)
    {
        Forward("cancel");
    }
    protected override void Save_Click(object sender, EventArgs e)
    {
        PortalUser user = PortalUser.FindByPrimaryKey(dlUser.SelectedValue);
        try
        {

            //for general
            CheckBox cbViewAdminTool = (CheckBox)FindControl(CHECKBOX_VIEW_ADMIN_TOOL);
            Permission pGeneral = Permission.Load(user.ID, Permission.VIEW_ADMIN_TOOL);
            if (pGeneral == null)
                pGeneral = new Permission();

            pGeneral.ModuleCanViewAdminTool = cbViewAdminTool.Checked;
            pGeneral.User_ID = user.ID;
            if (pGeneral.ID == 0)
                pGeneral.Save();
            else
                pGeneral.Update();

            //setpermission for Module
            CheckBox cbView, cbEdit, cbDelete;
            foreach (Module m in modules)
            {
                PortalObject po = PortalObject.FindByPrimaryKey(m.ID);
                Permission p = Permission.Load(user.ID, po.ID) ?? new Permission();
                cbView = (CheckBox)FindControl(CHECKBOX_MODULE_VIEW + m.ID);
                cbEdit = (CheckBox)FindControl(CHECKBOX_MODULE_EDIT + m.ID);
                cbDelete = (CheckBox)FindControl(CHECKBOX_MODULE_DELETE + m.ID);

                p.ModuleCanView = cbView.Checked;
                p.ModuleCanEdit = cbEdit.Checked;
                p.ModuleCanDelete = cbDelete.Checked;

                p.User_ID = user.ID;
                p.Object_ID = po.ID;
                if (p.ID == 0)
                    p.Save();
                else
                    p.Update();
            }

            CheckBox cbSubmit, cbApprove, cbPublish;
            foreach (Category cat in categories)
            {
                PortalObject po = PortalObject.FindByPrimaryKey(cat.ID);
                Permission p = Permission.Load(user.ID, po.ID) ?? new Permission();
                cbSubmit = (CheckBox)FindControl(CHECKBOX_CAT_SUBMIT + cat.ID);
                cbApprove = (CheckBox)FindControl(CHECKBOX_CAT_APPROVE + cat.ID);
                cbPublish = (CheckBox)FindControl(CHECKBOX_CAT_PUBLISH + cat.ID);

                p.WorkFlowCanSubmit = cbSubmit.Checked;
                p.WorkFlowCanApprove = cbApprove.Checked;
                p.WorkFlowCanPublish = cbPublish.Checked;

                p.User_ID = user.ID;
                p.Object_ID = po.ID;

                if (p.ID == 0)
                    p.Save();
                else
                    p.Update();
            }

            message.Text = string.Format("<div class='success'>Thiết lập danh sách quyền cho {0} thành công.</div>", user.Name);
            phPermission.Visible = false;
        }
        catch (Exception ex)
        {
            message.Text = string.Format("<div class='failed'>Thiết lập danh sách quyền cho {0} thất bại: {1}.</div>", user.Name, ex.Message);
            phPermission.Visible = true;
        }

    }
}